package com.central.scheduler.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.feign.ProjectService;
import com.central.common.model.*;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.scheduler.api.service.IProQueueService;
import com.central.scheduler.dao.mapper.QueueInfoMapper;
import com.central.scheduler.dao.model.ProQueue;
import com.central.scheduler.api.service.IQueueService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * @author Tindy
 * @date 2021/6/24
 * @describe
 */
@Slf4j
@Service
public class QueueServiceImpl extends SuperServiceImpl<QueueInfoMapper, QueueInfo> implements IQueueService {

    @Autowired
    private IProQueueService proQueueService;
    @Autowired
    private ProjectService projectService;

    @Override
    public PageResult<QueueInfo> findQueues(Map<String, Object> params) {
        Page<QueueInfo> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
        List<QueueInfo> list = baseMapper.findQueues(page, params);
        long total = page.getTotal();
        return PageResult.<QueueInfo>builder().data(list).code(0).count(total).build();
    }

    @Override
    public PageResult<QueueInfo> findQueuesByPro(Map<String, Object> params, Long proId) {
        Page<QueueInfo> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
        List<QueueInfo> list = baseMapper.findQueuesByPro(page, params,proId);
        long total = page.getTotal();
        return PageResult.<QueueInfo>builder().data(list).code(0).count(total).build();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setPros(Long queueId, Set<Long> proIds) {
        //删除旧项目
        proQueueService.remove(new QueryWrapper<ProQueue>().eq("queue_id",queueId));
        ArrayList<ProQueue> proQueues = new ArrayList<>();
        for (Long proId : proIds) {
            proQueues.add(new ProQueue(proId,queueId));
        }
        proQueueService.saveBatch(proQueues);
    }

    @Override
    public List<SysProject> getPros(Long workerId) {
        List<Long> proIds=proQueueService.getProIds(workerId);
        //处理空报错
        proIds.add(-1l);
        return projectService.findProByProIds(proIds);
    }
}
